package com.zhang.zhangapp.view.mine;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhang.zhangapp.MainActivity;
import com.zhang.zhangapp.PayResult;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.Constant;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.user.RechargeItem;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.utils.ActivityManager;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.BaseAppCompatActivityActivity;
import com.zhang.zhangapp.view.adapter.RechargeAdapter;
import com.zhang.zhangapp.view.custom.WrapHeightGridView;
import com.zhang.zhangapp.view.shop.BuyCouponActivity;
import com.zhang.zhangapp.wxapi.WXPayEntryActivity;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/13.
 */

@ContentView(R.layout.activity_recharge)
public class RechargeActivity extends BaseAppCompatActivityActivity {
    private final static int SDK_PAY_FLAG = 10000;
    @ViewInject(R.id.recharge_sure)
    TextView rechargeSure;
    @ViewInject(R.id.wx_pay)
    TextView wxPay;
    @ViewInject(R.id.ali_pay)
    TextView aliPay;
    @ViewInject(R.id.action_bar_title)
    TextView titleText;
    @ViewInject(R.id.recharge_grid_view)
    WrapHeightGridView gridView;
    RechargeAdapter rechargeAdapte;
    private IWXAPI iwxapi;
    //    private List<LinearLayout> rechargeLinearLayouts = new ArrayList<>();
    private List<RechargeItem> rechargeItemList = new ArrayList<>();


    private Map<String, String> rechargeParams = new HashMap<>();


    private LocalBroadcastManager localBroadcastManager;
    private PayReciver payReciver;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        initView();
        getRechareItems();
    }

    private void initView() {
        rechargeParams.put("memberId", MApplication.getInstance().getUser().getMemberId());
        rechargeParams.put("payMethod", "3");//付款方式 2:支付宝 3:微信 4:银联
        rechargeParams.put("rechargeAmount", "0.01");
        rechargeParams.put("largessAmount", "0");
        rechargeParams.put("realAmount", "0.01");
        rechargeAdapte = new RechargeAdapter(rechargeItemList, this);
        gridView.setAdapter(rechargeAdapte);
        wxPay.setSelected(true);
        aliPay.setSelected(false);
        titleText.setText("账户充值");
        initWxSdk();
        intLocalBroadcast();
    }

    private void initWxSdk() {
        iwxapi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
        iwxapi.registerApp(Constant.WX_APP_ID);
    }

    private void intLocalBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter(WXPayEntryActivity.PAY_SUCCESS);
        payReciver = new PayReciver();
        localBroadcastManager.registerReceiver(payReciver, intentFilter);

    }

    private void getRechareItems() {
        if (showLoadingDialog()) {
            CommonHttp.commonHttp("hzg/mainData/rechargeDesc", null, new MCallback() {
                @Override
                public void onSuccess(String data) {
                    Gson gson = new Gson();
                    List<RechargeItem> list = gson.fromJson(data, new TypeToken<List<RechargeItem>>() {
                    }.getType());
                    if (list != null)
                        rechargeItemList.addAll(list);
                    rechargeAdapte.notifyDataSetChanged();
                }

                @Override
                public void onSuccess(String message, String code) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    dismisionDalog();
                }
            });
        }
    }

    @Event(type = View.OnClickListener.class, value = {R.id.recharge_sure, //R.id.recharge1, R.id.recharge2, R.id.recharge3, R.id.recharge4,
            R.id.wx_pay, R.id.ali_pay, R.id.action_bar_left_image})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.recharge_sure:
                recharge();
                break;
            case R.id.ali_pay:
                wxPay.setSelected(false);
                aliPay.setSelected(true);
                rechargeParams.put("payMethod", "2");
                break;
            case R.id.wx_pay:
                wxPay.setSelected(true);
                aliPay.setSelected(false);
                rechargeParams.put("payMethod", "3");
                break;
            case R.id.action_bar_left_image:
                this.finish();
                break;
        }
    }


    private void recharge() {
        if (showLoadingDialog()) {
            RechargeItem rechargeItem = rechargeAdapte.getSelectedItem();
            //测试注释
//            rechargeParams.put("rechargeAmount", rechargeItem.getAmount());
//            rechargeParams.put("largessAmount", rechargeItem.getLargess());
//            rechargeParams.put("realAmount", rechargeItem.getAmount());
            CommonHttp.commonHttp("hzg/pay/recharge", rechargeParams, new MCallback() {
                @Override
                public void onSuccess(String data) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);

                        if (rechargeParams.get("payMethod").equals("3")) {
                            String transNo = jsonObject.getString("transNo");
                            JSONObject reqStr = jsonObject.getJSONObject("reqStr");
                            sendPayRequest(reqStr, transNo);
                        } else {
                            String transNo = jsonObject.getString("transNo");
                            String reqStr = jsonObject.getString("reqStr");
                            aliPay(reqStr);
                        }
                    } catch (Exception e) {

                    }
                    //Recharge recharge = gson.fromJson(data, Recharge.class);
                    //T.showShort(RechargeActivity.this,"支付功能稍后接入");
                }

                @Override
                public void onSuccess(String message, String code) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    dismisionDalog();
                }
            });
        }
    }

    /**
     * 调用微信支付
     */
    public void sendPayRequest(JSONObject object, String transaction) {
        try {
            PayReq req = new PayReq();
            req.appId = object.getString("appid");
            req.partnerId = object.getString("partnerid");
            //预支付订单
            req.prepayId = object.getString("prepayid");
            req.nonceStr = object.getString("noncestr");
            req.timeStamp = object.getString("timestamp");
            req.packageValue = object.getString("package");
            req.sign = object.getString("sign");
            req.transaction = transaction;
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            //3.调用微信支付sdk支付方法
            iwxapi.sendReq(req);
        } catch (Exception e) {
        }

    }

    private void aliPay(final String payInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RechargeActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

// 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if ("9000".equals(resultStatus)) {
                        Toast.makeText(RechargeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        ((MainActivity) ActivityManager.getActivityManager().getActivty(MainActivity.class)).updateUserInfo();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if ("8000".equals(resultStatus)) {
                            Toast.makeText(RechargeActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(RechargeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(payReciver);
    }

    class PayReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            T.showShort(RechargeActivity.this, "本地通知");
//            ActivityManager.getActivityManager().finishActivity(WXPayEntryActivity.class);
        }
    }

}
